local skynet = require "skynet"
require "skynet.manager"

local queue = {}

local CMD = {}

function CMD.start()
end

function CMD.stop()
end

function CMD.sync(sql)
    table.insert(queue, sql)
end

function CMD.tick()
    for k, sql in pairs(queue) do
        skynet.send("mysql_service", "lua", "execute", sql)
        queue[k] = nil
    end
    -- queue = {}
end

-- local function sync_impl()
--     while true do
--         for k, sql in pairs(queue) do
--             skynet.call("mysql_service", "lua", "execute", sql)
--             queue[k] = nil
--         end
--         skynet.sleep(500)
--     end
-- end

local function loop()
    while true do       
        if queue[1] then
            skynet.send(skynet.self(), 'lua', 'tick')
        end
        skynet.sleep(50)--
    end
end

skynet.start(function()
    skynet.dispatch("lua", function(session, source, cmd, ...)
        -- local f = assert(CMD[cmd], cmd .. "not found")
        local f = CMD[cmd]
        if type(f) == 'function' then 
            skynet.retpack(f(...))
        end
    end)
    skynet.fork(loop)
    skynet.register(SERVICE_NAME)
end)

